package me.xhy.java.springboot3.r2dbc.s01meet;

import io.asyncer.r2dbc.mysql.MySqlConnectionConfiguration;
import io.asyncer.r2dbc.mysql.MySqlConnectionFactory;
import io.asyncer.r2dbc.mysql.api.MySqlConnection;
import me.xhy.java.springboot3.r2dbc.s00application.S002Entity;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

public class S011Meet {

  @Test
  public void connection() throws Exception {
    // r2dbc 全异步、非阻塞、响应式、消息驱动

    // 1. 数据库链接配置
    MySqlConnectionConfiguration configuration = MySqlConnectionConfiguration.builder()
        .host("localhost")
        .port(3306)
        .username("root")
        .password("123123")
        .database("x-study-1")
        .build();

    // 2. 创建链接
    MySqlConnectionFactory connectionFactory = MySqlConnectionFactory.from(configuration);
    Mono<? extends MySqlConnection> MySqlConnection = Mono.from(connectionFactory.create());


    // 3. 发送sql执行
    // 用 Mono 提取 connection 中的元素
    MySqlConnection
        .flatMapMany(connection ->
            connection
                .createStatement("select * from xs1_t_demo1 where dept_id = ?dept_id")
                .bind("dept_id", 1L) //具名参数
                .execute()
        ).flatMap(result -> {
          return result.map(readable -> {
            Long id = readable.get("id", Long.class);
            Long deptId = readable.get("dept_id", Long.class);
            return new S002Entity(String.valueOf(id), String.valueOf(deptId));
          });
        })
        .subscribe(item -> System.out.println("S012Entity = " + item))
    ;

    TimeUnit.SECONDS.sleep(10);
  }

}
